<div class="animated fadeIn">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-align-justify"></i>空间管理
                </div>
                <div class="card-body">

                    <div class="layui-row">
                        <div class="layui-col-md6">

                            <div class="container">
                                <table class="layui-disk" id="LAY_table_disks" lay-filter="disk">
                                </table>

                                <script type="text/html" id="diskOpsBar">
                                    <div class="layui-btn-group">
                                        <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="edit-disk">
                                            <i class="fas fa-edit" title="编辑"></i>
                                        </button>
                                        <button class="layui-btn layui-btn-warm layui-btn-sm" lay-event="auth-disk">
                                            <i class="fas fa-user-secret" title="授权"></i>
                                        </button>
                                        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="delete">
                                            <i class="fas fa-trash-alt" title="删除"></i>
                                        </button>
                                    </div>
                                </script>
                            </div>
                        </div>
                        <div class="layui-col-md6" style="float: right">

                            <div class="container">
                                <div class="layui-btn-group">
                                    <a class="layui-btn layui-btn-sm" lay-filter="add"><i
                                            class="fas fa-plus-square"></i> 新建目录</a>
                                    <a id="authFolderBtn" class="layui-btn layui-btn-sm layui-btn-warm"
                                       lay-filter="auth-folder"><i class="fas fa-user-secret"></i> 授权管理</a>
                                </div>

                                <ul id="diskFolderTree" class="ztree"></ul>

                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <!--/.row-->
        </div>
    </div>
</div>

<!-- 模态框 -->
<div class="modal fade" id="addDisk">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">

            <!-- 模态框头部 -->
            <div class="modal-header">
                <h4 class="modal-title">磁盘空间</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- 模态框主体 -->
            <div class="modal-body">
                <div class="table-responsive" style="text-align: center">
                    <form method="POST" th:action="@{'./disk/save'}">
                        <table class="table table-hover">
                            <tr>
                                <td align="right">磁盘空间名:</td>
                                <td>
                                    <div class="template-input-icon-container">
                                        <i class="fas fa-hdd"></i>
                                        <input type="text" class="form-control"
                                               placeholder="磁盘空间名"
                                               required="required"
                                               id="diskName" name="diskName"/>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">所有者名称:</td>
                                <td>
                                    <div class="template-input-icon-container">
                                        <i class="fas fa-user-secret"></i>
                                        <input type="text" class="form-control"
                                               placeholder="所有者名称"
                                               required="required"
                                               id="owner" name="owner"/>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">所有者类别:</td>
                                <td>
                                    <select id="authType" name="authType"
                                            class="select custom-select">
                                        <option th:each="entry : ${authTypeMap}"
                                                th:value="${entry.key}"
                                                th:text="${entry.value}">所有者类别
                                        </option>
                                    </select>
                                </td>
                            </tr>
                        </table>
                        <input type="submit" value="保存" class="btn btn-success"/>
                    </form>
                </div>
            </div>
            <!-- 模态框底部 -->
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭
                </button>
            </div>

        </div>
    </div>
</div>

<link href="../css/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css">

<style type="text/css">
    .ztree li span.button.add {
        margin-left: 2px;
        margin-right: -1px;
        background-position: -144px 0;
        vertical-align: top;
        *vertical-align: middle
    }
</style>
<script src="../js/jquery.ztree.all.js" type="text/javascript"></script>
<script th:inline="javascript">
    /*<![CDATA[*/

    layui.use(['table', 'upload'], function () {
        var table = layui.table,
            diskId = null;

        var optDisk = {
            elem: '#LAY_table_disks',
            id: 'disk-data',
            url: '/api/disk/list1',
            height: '520',
            page: false,
            limit: 10,
            limits: [10, 50, 100, 200],
            cols: [
                [
                    {field: 'id', title: 'ID'},
                    {field: 'name', title: '磁盘名称', event: 'diskName'},
                    {field: 'authorizations', title: '授权信息'},
                    {
                        title: '操作',
                        align: 'center',
                        toolbar: '#diskOpsBar'
                    }
                ]
            ],
            done: function (res, curr, count) {
                $("[data-field='id']").css('display', 'none');
            }
        };

        //方法级渲染
        table.render(optDisk);

        table.on('tool(disk)', function (obj) {
            var data = obj.data;
            if (obj.event === 'diskName') {
                diskId = data.id;
                loadDiskFolders(diskId);
            } else if (obj.event === 'edit-disk') {
                layer.prompt(
                    {
                        title: '请输入新的磁盘名称',
                        success: function (layerInput) {
                            layerInput.find('input').on('keydown', function () {
                                if (event.keyCode === 13) {
                                    prompt_service(event.target.value);
                                }
                            })
                        }
                    },
                    function (value) {
                        prompt_service(value);
                    }
                );

                function prompt_service(inputParam) {
                    var codeParam = encodeURI(inputParam);
                    $.ajax({
                        type: "POST",
                        url: "/api/disk/rename?diskId=" + data.id + "&newName=" + codeParam,
                        contentType: 'application/json; charset=utf-8',
                        dataType: "json",
                        success: function (value) {
                            var tableDisk = table.render(optDisk);
                            tableDisk.reload();
                        }
                    });
                    layer.closeAll();
                }
            } else if (obj.event === 'auth-disk') {
                layer.open({
                    type: 2,
                    title: '磁盘授权',
                    area: ['560px', '420px'],
                    resize: false,
                    content: 'disk/auth?id=' + data.id + '&target=DISK',
                    zIndex: layer.zIndex,
                    success: function (layero) {
                        layer.setTop(layero);
                    }
                });
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除磁盘: ' + data.name + ' 吗？', {title: "删除确认"}, function (index) {
                    $.ajax({
                        type: "POST",
                        url: "/api/disk/delete",
                        contentType: 'application/json; charset=utf-8',
                        data: data.id, //可选参数
                        dataType: "json",
                        success: function (value) {
                            var result = JSON.parse(value);
                            if (result == true) {
                                layer.alert('磁盘【' + data.name + '】删除成功!', {
                                    icon: 6, btn: ['确认'], yes: function (index) {
                                        obj.del();
                                        layer.close(index);
                                        var tableDisk = table.render(optDisk);
                                        tableDisk.reload();
                                    }
                                });
                            } else {
                                layer.alert("磁盘删除失败!", {icon: 2});
                            }
                            layer.close(index);
                        }
                    });
                });
            }
        });

        $('.layui-btn').on('click', function () {
            switch ($(this).attr('lay-filter')) {
                case 'add': {
                    promptAddFolder(null, 'sibling');
                }
                    break;
                case 'auth-folder': {
                    var zTree = $.fn.zTree.getZTreeObj("diskFolderTree"),
                        nodes = zTree.getCheckedNodes(true);
                    layer.open({
                        type: 2,
                        title: '目录授权',
                        area: ['560px', '420px'],
                        resize: false,
                        content: 'disk/auth?id=' + nodes[0].id + '&target=FOLDER',
                        zIndex: layer.zIndex,
                        success: function (layero) {
                            layer.setTop(layero);
                        }
                    });
                }
                    break;
            }
        });

        function promptAddFolder(selectedRow, addType) {
            layer.prompt(
                {
                    title: '请输入目录名',
                    success: function (layerInput) {
                        layerInput.find('input').on('keydown', function () {
                            if (event.keyCode === 13) {
                                saveFolderService(event.target.value, selectedRow, addType);
                            }
                        })
                    }
                },
                function (value) {
                    saveFolderService(value, selectedRow, addType);
                }
            );
        }

        function saveFolderService(folderName, selectedRow, addType) {
            var parentId = null;
            var parentType = null;
            var folderNameCode = encodeURI(folderName);
            switch (addType) {
                case 'sibling': {
                    if (selectedRow === null) {
                        parentId = diskId;
                    } else {
                        parentId = selectedRow.parentId;
                    }
                    if (parentId === diskId) {
                        parentType = 'DISK';
                    } else {
                        parentType = 'FOLDER';
                    }
                }
                    break;
                case 'child': {
                    parentId = selectedRow.id;
                    parentType = 'FOLDER';
                }
                    break;
            }
            $.ajax({
                type: "POST",
                url: "/api/folder/save?name=" + folderNameCode + "&parentId=" + parentId + "&parentType=" + parentType + "&diskId=" + diskId,
                contentType: 'application/json; charset=utf-8',
                //data: JSON.stringify(postData), //可选参数
                dataType: "json",
                success: function (value) {
                    var zTree = $.fn.zTree.getZTreeObj("diskFolderTree");
                    zTree.addNodes(selectedRow, value);
                }
            });
            layer.closeAll();
        }

        function loadDiskFolders(_diskId) {
            $.ajax({
                type: "GET",
                url: "/api/folder/list?diskId=" + _diskId,
                contentType: 'application/json; charset=utf-8',
                //data: data.id, //可选参数
                dataType: "json",
                success: function (value) {
                    $.fn.zTree.init($("#diskFolderTree"), setting, value);
                }
            });
        }

        var setting = {
            view: {
                dblClickExpand: false,
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            },
            data: {
                key: {
                    isParent: "parent"
                },
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: null
                }
            },
            edit: {
                enable: true,
                editNameSelectAll: true,
                showRemoveBtn: showRemoveBtn,
                showRenameBtn: true
            },
            callback: {
                beforeRemove: beforeRemove,
                beforeRename: beforeRename,
                onRemove: onRemove,
                onRename: onRename
            }
        };

        function showRemoveBtn(treeId, treeNode) {
            return !treeNode.parent;
        }

        function beforeRemove(treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("diskFolderTree");
            zTree.selectNode(treeNode);
            layer.confirm('真的删除目录: ' + treeNode.name + ' 吗？', {title: "删除确认"}, function (index) {
                $.ajax({
                    type: "POST",
                    url: "/api/folder/delete?id=" + treeNode.id,
                    contentType: 'application/json; charset=utf-8',
                    //data: data.id, //可选参数
                    dataType: "json",
                    success: function (res) {
                        zTree.removeNode(treeNode, false);
                        layer.close(index);
                    }
                });
            });
            return false;
        }

        function onRemove(e, treeId, treeNode) {
            // 留空
        }

        function beforeRename(treeId, treeNode, newName, isCancel) {
            if (newName.length == 0) {
                setTimeout(function () {
                    var zTree = $.fn.zTree.getZTreeObj("diskFolderTree");
                    zTree.cancelEditName();
                    layer.alert("节点名称不能为空!", {icon: 2});
                }, 0);
                return false;
            }
            return true;
        }

        function onRename(e, treeId, treeNode, isCancel) {
            $.ajax({
                type: "POST",
                url: "/api/folder/rename?id=" + treeNode.id + "&newName=" + treeNode.name,
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                success: function (value) {
                    // 界面反馈REST调用结果
                }
            });
        }

        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='新建目录' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_" + treeNode.tId);
            if (btn) btn.bind("click", function () {
                promptAddFolder(treeNode, 'child');
                return false;
            });
        }

        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_" + treeNode.tId).unbind().remove();
        }

        /*]]>*/
    });
</script>